package utils

import (
	"crypto/x509"
	"encoding/pem"
	"github.com/golang-jwt/jwt/v4"
	"time"
)

// 定义 JWT 声明结构体
type Claims struct {
	// 嵌入标准的 JWT 声明
	jwt.StandardClaims
}

func GetMarketAppJWTToken(pemFile, appId string) string {

	file, err := ReadTemplateFile(pemFile)
	if err != nil {
		return ""
	}
	expireTime := time.Now().Add(1 * 24 * time.Hour)
	issuedTime := time.Now()
	claims := &Claims{
		jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(),
			IssuedAt:  issuedTime.Unix(),
			Issuer:    appId,
		},
	}
	privateData, _ := pem.Decode([]byte(file))
	privateKey, _ := x509.ParsePKCS8PrivateKey(privateData.Bytes)
	token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)

	tokenString, err := token.SignedString(privateKey)
	if err != nil {
		return ""
	}
	return tokenString
}
